package edu.erpan.bl.bean;

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateful;
import javax.persistence.Query;

import edu.erpan.bl.entities.Formulacion;
import edu.erpan.bl.entities.Producto;
import edu.erpan.util.entityManager.GenericEntityManager;
import edu.erpan.util.entityManager.exceptions.PersistException;
import edu.erpan.util.entityManager.exceptions.QueryException;

/**
 * Session Bean implementation class ProductoBean
 */
@Stateful
@LocalBean
public class ProductoBean extends GenericEntityManager<Producto> implements ProductoBeanRemote<Producto> {

	 
    /**
     * Default constructor. 
     */
    public ProductoBean() {
        // TODO Auto-generated constructor stub
    	super(Producto.class);
    }

	@Override
	public void guardarFormulacion(Formulacion formulacion)
			throws PersistException {
		try{
			this.getEntityManager().merge(formulacion);
		}catch (Exception e) {
    		throw new PersistException(e);
		}
	}

	@Override
	public void editarFormulacion(Formulacion formulacion)
			throws QueryException {
		try{
			this.getEntityManager().merge(formulacion);
		}catch (Exception e) {
    		throw new QueryException(e);
		}
		
	}

	@Override
	public void eliminarFormulacion(Formulacion formulacion)
			throws QueryException {
		try{
			formulacion=this.getEntityManager().getReference(Formulacion.class, formulacion.getIdformulacion());
			this.getEntityManager().remove(formulacion);
		}catch (Exception e) {
    		throw new QueryException(e);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Formulacion> consultarFormulaciones(Producto producto)
			throws QueryException {
		String stringQuery="SELECT formulacion FROM "+Formulacion.class.getName()+" formulacion WHERE formulacion.producto.idproducto = ? ORDER BY formulacion.materiaPrima.nombre ASC";
		
		List<Formulacion>formulaciones=null;
		try{
			Query query=this.getEntityManager().createQuery(stringQuery);
			query.setParameter(1, producto.getIdproducto());
			
			formulaciones=query.getResultList();
		}catch (Exception e) {
			throw new QueryException(e);
		}
		return formulaciones;
	}
}
